/*
 * Copyright (c) 2006, 2023, webrx.cn All rights reserved.
 *
 */
package cn.webrx.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Field;

/**
 * <p></p>
 * <p>Powered by webrx On 2023-04-20 17:30:19</p>
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class DemoInterceptor implements Interceptor {

    private String getBound(Invocation invocation) {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Configuration configuration = ms.getConfiguration();
        Object parameter = args[1];
        Object target = invocation.getTarget();
        StatementHandler handler = configuration.newStatementHandler((Executor) target, ms, parameter, RowBounds.DEFAULT, null, null);
        return handler.getBoundSql().getSql();
    }

    /**
     * 回塞sql
     *
     * @param ms           MappedStatement
     * @param newSqlSource SqlSource
     * @return MappedStatement
     */
    private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //System.out.println("Object intercept(Invocation invocation)...........................拦截器执行");
        //Method method = invocation.getMethod();
        //System.out.println(method.getName()); //update
        //Object target = invocation.getTarget();
        //System.out.println(target.getClass().getSimpleName());

        //Object[] args = invocation.getArgs();
        //System.out.println(Arrays.toString(args));
        //
        //MappedStatement ms = (MappedStatement) args[0];
        //cn.webrx.mapper.BookMapper.add
        //System.out.println(ms.getId());

        //StatementType statementType = ms.getStatementType();
        //System.out.println(statementType); //STATEMENT  PREPARED CALLABLE

        //SqlSource sqlSource = ms.getSqlSource();
        //BoundSql boundSql = sqlSource.getBoundSql(ms.getParameterMap());
        //System.out.println(boundSql.getSql());
        //System.out.println(getBound(invocation));


        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        BoundSql boundSql = mappedStatement.getBoundSql(args[1]);
        //  获取到原始sql
        String sql = boundSql.getSql();
        System.out.println(sql);


        //新sql语句
        Field field = boundSql.getClass().getDeclaredField("sql");
        field.setAccessible(true);
        // 改造的sql塞回去  newSql 为改造之后的sql
        field.set(boundSql, "insert into t_book values (123, ?, ?, ?, ?)");
        System.out.println(boundSql.getSql());


        //将旧的mappedStatement 换为 新的 copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(boundSql)) 返回新的将旧的mappedStatement
        args[0] = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(boundSql));


        //ParameterMap param = ms.getParameterMap();
        //System.out.println("-------------");
        //System.out.println(param.getId());
        //System.out.println(param.getType());
        //System.out.println(param.getParameterMappings());

        //Book book = (Book)args[1];
        //Class<?> arg = args[1].getClass();


        //SqlCommandType sqlCommandType = ms.getSqlCommandType();
        //System.out.println(sqlCommandType);// SqlCommandType.INSERT SqlCommandType.DELETE SqlCommandType.UPDATE
        Object obj = invocation.proceed();
        return obj;
    }

    public static class BoundSqlSqlSource implements SqlSource {
        BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }

}
